package com.example.demo.thread;

import java.util.concurrent.TimeUnit;

/**
 * @Author: liull
 * @Description: 理解线程中断 根据中断判断线程是否终止的例子
 * @Date: Created in 13:51 2021/7/9
 * @Modified By:
 */

/**
 * Thread begin sleep 20 s
 * main thread interrupt thread
 * Thread is interrupted while sleeping
 * main is over.
 */
public class InterruptedTest2 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("Thread begin sleep 20 s");
                TimeUnit.SECONDS.sleep(20);
                System.out.println("Thread awaking");

            } catch (InterruptedException e) {
                System.out.println("Thread is interrupted while sleeping");
                return;
            }
            System.out.println("thread leaving normally");
        });

        thread.start();

        // 主线程休眠1s 以便中断前让子线程输出
        Thread.sleep(1000);

        System.out.println("main thread interrupt thread");
        thread.interrupt();

        // 等待子线程执行完毕
        thread.join();
        System.out.println("main is over.");
    }
}
